import type { Rule } from 'antd/es/form'
import type { ColumnsType } from 'antd/es/table'
import { type FC, useState, useEffect } from 'react'
import type { GetProp, TreeSelectProps } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import {
  Card,
  Form,
  Input,
  Button,
  DatePicker,
  Select,
  TreeSelect,
  Space,
  Table,
  Tag,
  Popover,
  Switch,
  type TableProps,
  Modal,
  ConfigProvider,
  Checkbox
} from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'
import { PageWrapper } from '@/components/Page'
import type { APIResult, PageState, TableDataType } from '@/views/table/table-basic/types'
import { getTableList } from '@/api'

type DefaultOptionType = GetProp<TreeSelectProps, 'treeData'>[number]
const { RangePicker } = DatePicker
const marriedOptions = [
  { label: '单身', value: 0 },
  { label: '未婚', value: 1 },
  { label: '已婚', value: 2 },
  { label: '离异', value: 3 }
]
let localLang: any = localStorage.getItem('language')
const browserLang = navigator.language
if (!localLang) {
  localLang = browserLang === 'zh-CN' ? zhCN : ''
} else {
  localLang = localLang === 'zh' ? zhCN : ''
}
// console.log('localLang==', localLang)

const BasicPage: FC = () => {
  const [searchForm] = Form.useForm()
  const [formState] = useState({
    orderNo: '',
    createBy: '',
    dateVal: '',
    approveStatus: undefined,
    approveStatusList: [
      { label: '待审核', value: '1' },
      { label: '审核已通过', value: '2' },
      { label: '审核未通过', value: '3' },
      { label: '逾期未审核', value: '4' },
      { label: '审核中', value: '5' },
      { label: '撤回', value: '7' }
    ],
    borrowState: undefined,
    borrowStateList: [
      { label: '未借出', value: 0 },
      { label: '未归还', value: 1 },
      { label: '超时未归还', value: 2 },
      { label: '已归还', value: 3 }
    ],
    departmentId: undefined
  })

  const formRules: Record<string, Rule[]> = {
    orderNo: [{ required: true, message: '单号不能为空' }],
    createBy: [{ required: true, message: '申请人不能为空' }],
    password: [
      { required: true, message: '内容不能为空' },
      { min: 6, max: 16, message: '密码长度在 6 到 16 个字符' },
      { pattern: /^[a-zA-Z0-9_-]{6,16}$/, message: '密码只支持字母、数字和下划线' }
    ]
  }

  const [treeData, setTreeData] = useState<Omit<DefaultOptionType, 'label'>[]>([
    { id: 1, pId: 0, value: '1', title: 'Expand to load' },
    { id: 2, pId: 0, value: '2', title: 'Expand to load' },
    { id: 3, pId: 0, value: '3', title: 'Tree Node', isLeaf: true }
  ])

  const genTreeNode = (parentId: number, isLeaf = false) => {
    const random = Math.random().toString(36).substring(2, 6)
    return {
      id: random,
      pId: parentId,
      value: random,
      title: isLeaf ? 'Tree Node' : 'Expand to load',
      isLeaf
    }
  }

  const onLoadData: TreeSelectProps['loadData'] = ({ id }) =>
    new Promise(resolve => {
      setTimeout(() => {
        setTreeData(treeData.concat([genTreeNode(id, false), genTreeNode(id, true), genTreeNode(id, true)]))
        resolve(undefined)
      }, 300)
    })

  const [tableLoading, setTableLoading] = useState(false)
  const [tableData, setTableData] = useState<TableDataType[]>([])
  const [tableTotal, setTableTotal] = useState<number>(0)
  const [tableQuery, setTableQuery] = useState<PageState>({ current: 1, pageSize: 10 })
  const [modalVisible, setModalVisible] = useState<boolean>(false)
  const [editHobby, setEditHobby] = useState<string[]>([])
  const [modalForm] = Form.useForm()

  const columns: ColumnsType<TableDataType> = [
    {
      title: '编号',
      dataIndex: 'id',
      align: 'center',
      sorter: false
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
      render: (_, record: any) => {
        const content = (
          <div>
            <p>姓名: {record.name}</p>
            <p>手机: {record.phone}</p>
            <p>爱好: {record.hobby.join('、')}</p>
          </div>
        )
        return (
          <Popover content={content}>
            <Tag color='orange'>{record.name}</Tag>
          </Popover>
        )
      }
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center'
    },
    {
      title: '手机',
      dataIndex: 'phone',
      align: 'center'
    },
    {
      title: '学历',
      dataIndex: 'education',
      align: 'center'
    },
    {
      title: '婚姻状况',
      dataIndex: 'married',
      align: 'center',
      render: (text, record: any) => (
        <Select options={marriedOptions} defaultValue={record.married} onChange={value => (record.married = value)} />
      )
    },
    {
      title: '禁止编辑',
      dataIndex: 'forbid',
      align: 'center',
      render: (_, record: any) => (
        <Switch defaultChecked={record.forbid} onChange={checked => (record.forbid = checked)} />
      )
    },
    {
      title: '爱好',
      dataIndex: 'hobby',
      align: 'center',
      render: (_, record: any) => <span>{record.hobby.join('、')}</span>
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record: any) => (
        <Space>
          <Button type='primary' size='small' disabled={record.forbid} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button size='small' danger onClick={handleDelete}>
            删除
          </Button>
        </Space>
      )
    }
  ]

  const tableSelection: TableProps<any>['rowSelection'] = {
    onChange: (selectedRowKeys: any[]) => {
      console.log(selectedRowKeys)
    }
  }

  const fetchData = async () => {
    setTableLoading(true)
    const data = await getTableList(tableQuery)
    const { list, total } = data as unknown as APIResult
    setTableData(list)
    setTableTotal(total)
    setTableLoading(false)
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setTableQuery({ ...tableQuery, current: page, pageSize })
  }

  const handleDelete = () => {
    Modal.confirm({
      title: '删除确认！',
      icon: <ExclamationCircleOutlined rev={undefined} />,
      content: '此操作将删除选中数据, 是否继续?',
      // okType: 'danger',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        console.log('OK')
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }

  const handleEdit = (record: TableDataType) => {
    modalForm.setFieldsValue({ ...record })
    setEditHobby(record.hobby)
    setModalVisible(true)
    // console.log('record==', record)
  }

  const handleConfirm = () => {
    setModalVisible(false)
  }

  const handleCancel = () => {
    setEditHobby([])
    setModalVisible(false)
  }

  useEffect(() => {
    fetchData().then(r => {})
  }, [tableQuery])

  return (
    <PageWrapper>
      <Card bordered={false}>
        <ConfigProvider locale={localLang}>
          {/*搜索*/}
          <Form
            form={searchForm}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 22 }}
            initialValues={{ ...formState }}
            style={{ width: '100%', margin: '0 auto', display: 'flex', flexWrap: 'wrap' }}
          >
            <Form.Item label='' name='orderNo' rules={formRules.orderNo}>
              <Input style={{ width: 150, marginRight: 10 }} placeholder='请输入单号' />
            </Form.Item>
            <Form.Item label='' name='departmentId'>
              <TreeSelect
                style={{ width: 180, marginRight: 10 }}
                value={formState.departmentId}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                loadData={onLoadData}
                treeData={treeData}
                treeDataSimpleMode
                placeholder='请选择部门'
              />
            </Form.Item>
            <Form.Item label='' name='createBy' rules={formRules.createBy}>
              <Input style={{ width: 150, marginRight: 10 }} placeholder='请输入申请人' />
            </Form.Item>
            <Form.Item label='' name='dateVal'>
              <RangePicker style={{ width: 250 }} />
            </Form.Item>
            <Form.Item label='' name='approveStatus'>
              <Select
                style={{ width: 150, marginLeft: 10 }}
                allowClear
                options={formState.approveStatusList.map(t => ({ label: t.label, value: t.value }))}
                placeholder='请选择审核状态'
              />
            </Form.Item>
            <Form.Item label='' name='borrowState'>
              <Select
                style={{ width: 150, marginLeft: 10 }}
                allowClear
                options={formState.borrowStateList.map(t => ({ label: t.label, value: t.value }))}
                placeholder='请选择借用状态'
              />
            </Form.Item>
            <Form.Item style={{ width: 160, marginLeft: 10 }}>
              <Button type='primary' onClick={fetchData}>
                查询
              </Button>
              <Button style={{ marginLeft: 10 }}>重置</Button>
            </Form.Item>
          </Form>
          {/*列表*/}
          <Table
            rowKey='id'
            rowSelection={tableSelection}
            columns={columns}
            dataSource={tableData}
            loading={tableLoading}
            pagination={{
              current: tableQuery.current,
              pageSize: tableQuery.pageSize,
              total: tableTotal,
              showTotal: () => `共 ${tableTotal} 条`,
              showSizeChanger: true,
              showQuickJumper: true,
              onChange: handlePageChange
            }}
          />
          {/*编辑弹窗*/}
          <Modal
            title='编辑'
            width={600}
            open={modalVisible}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText='提交'
            cancelText='关闭'
            maskClosable={false}
          >
            <Form
              form={modalForm}
              colon={false}
              labelCol={{ span: 3 }}
              labelAlign='left'
              style={{ width: '85%', margin: '0 auto' }}
            >
              <Form.Item label='姓名' name='name'>
                <Input disabled />
              </Form.Item>
              <Form.Item label='手机' name='phone'>
                <Input placeholder='请输入手机号码' />
              </Form.Item>
              <Form.Item label='学历' name='education'>
                <Select options={['初中', '高中', '大专', '本科'].map(item => ({ value: item }))} />
              </Form.Item>
              <Form.Item label='爱好' name='hobby'>
                <Checkbox.Group options={editHobby.map(item => ({ label: item, value: item }))} />
              </Form.Item>
            </Form>
          </Modal>
        </ConfigProvider>
      </Card>
    </PageWrapper>
  )
}

export default BasicPage
